package com.github.natholdallas.controller

import cn.dev33.satoken.annotation.SaIgnore
import cn.dev33.satoken.stp.StpUtil
import com.github.natholdallas.common.ApiViews
import com.github.natholdallas.common.UNIQUE_UUID
import com.github.natholdallas.common.Views
import com.github.natholdallas.database.Users
import com.github.natholdallas.declaration.Body
import com.github.natholdallas.declaration.Param
import com.github.natholdallas.declaration.Path
import com.github.natholdallas.declaration.Response
import com.github.natholdallas.etc.imagePath
import com.github.natholdallas.etc.imagePreview
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.boot.autoconfigure.web.ErrorProperties
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.servlet.ModelAndView


@ApiViews("/account")
class AccountCtl(private val users: Users) {

    @[PostMapping("/login") SaIgnore]
    fun login(@Body data: LoginIn): LoginToken {
        val user = users.findLogin(data.username, data.password)
        StpUtil.login(user.id)
        return LoginToken(user.role)
    }

    @[PostMapping("/logout")]
    fun logout() {
        StpUtil.logout()
    }

}


@ApiViews("/upload")
class UploadCtl {

    @[PostMapping]
    fun uploadImage(@Param file: MultipartFile): Map<String, String> {
        val filename = "$UNIQUE_UUID${file.originalFilename?.run { substring(lastIndexOf('.')) }}"
        file.transferTo(kotlin.io.path.Path("$imagePath/$filename"))
        return mapOf(Pair("value", "$imagePreview/$filename"))
    }

}


@Views("/{path:[^.]*}")
class IndexController {

    @[GetMapping]
    fun index(@[Suppress("UNUSED_PARAMETER") Path] path: String) = "forward:/index.html"

}


@Views
class ErrorCtl : BasicErrorController(DefaultErrorAttributes(), ErrorProperties()) {

    override fun errorHtml(request: HttpServletRequest?, response: HttpServletResponse?) = ModelAndView(
        buildString { append("/") }
    )

    override fun error(request: HttpServletRequest?) = Response<MutableMap<String, Any>>(
        mutableMapOf(), getStatus(request)
    )

}
